package cn.yusei.teamTribe.service.user;

import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import cn.yusei.teamTribe.dao.JedisDAO;

@Service
public class TokenService implements InitializingBean{

	@Autowired
	JedisDAO jedisDAO;
	
	@Value("${tokenValidDay}")
	private int tokenValidDay;
	@Value("${idListenSecond}")
	private int idListenSecond;		//在idListenSecond时间内，如果用户重复登录，会删除原来的token
	
	private static final String VALUE_SPLIT_CHAR = "_";
	private static final int ID_INDEX = 0;
	private static final int SCHOOL_ID_INDEX = 1;
	
	public void afterPropertiesSet()
	{
		tokenValidDay = tokenValidDay * 60 * 60 * 24;
	}
	
	public void addToken(int id, String token)
	{
		String session = jedisDAO.get(String.valueOf(id));
		if(session != null)
			jedisDAO.del(session);
		String tokenKey = token;
		String tokenValue = id + VALUE_SPLIT_CHAR + -1;
		jedisDAO.setex(tokenKey, tokenValidDay, tokenValue);
		jedisDAO.setex(tokenValue, idListenSecond, tokenKey);
	}
	
	public void deleteToken(String token)
	{
		jedisDAO.del(token);
	}

	private String[] getTokenArray(String teamTribeToken)
	{
		String tokenString = null;
		tokenString = jedisDAO.get(teamTribeToken);
		if(tokenString == null)
			return null;
		jedisDAO.setex(teamTribeToken, tokenValidDay, tokenString);
		return tokenString.split(VALUE_SPLIT_CHAR);
	}
	
	public Integer getId(String teamTribeToken)
	{
		Integer id = null;
		try
		{
			id = Integer.valueOf(getTokenArray(teamTribeToken)[ID_INDEX]);
		}
		catch (Exception e)
		{
			// 没有找到 id ,直接返回 null
			return null;
		}
		return id;
	}
	
	public Integer getSchoolId(String teamTribeToken)
	{
		Integer schoolId = null;
		try
		{
			schoolId = Integer.valueOf(getTokenArray(teamTribeToken)[SCHOOL_ID_INDEX]);
		}
		catch (Exception e)
		{
			//没有找到 schoool ，直接返回null
			return null;
		}
		return schoolId;
	}
}
